const   Router = require('koa-router')
const mongoose = require('mongoose')

let router = new Router()


router.post('/fabwz',async(ctx)=>{
    //取得Model
    const Article = mongoose.model('Article')
    //把从前端接收的POST数据封装成一个新的Article对象
    let newArticle = new Article(ctx.request.body)
    //用mongoose的save方法直接存储，然后判断是否成功，返回相应的结果
    await newArticle.save().then(()=>{
        //成功返回code=200，并返回成功信息
        ctx.body={
            code:200,
            message:'发表成功'
        }
    }).catch(error=>{
         //失败返回code=500，并返回错误信息
        ctx.body={
            code:500,
            message:error
        }
    })
})

router.post('/home', async (ctx)=>{
    const Article = mongoose.model('Article')

    await Article.find({}).exec().then( async (result)=>{
        ctx.body = {
            code:200,
            message:result
        }
    }).catch(err=>{
        console.log(err)
        ctx.body = {
            code:500,
            message:err
        }
    })
})

router.post('/del', async(ctx)=>{
    const Article = mongoose.model('Article')
        //等待前台传过来id
    let ArticleId = ctx.request.body.ArticleId
    console.log(ArticleId)
    await Article.deleteOne({"_id":ArticleId}).exec().then(result=>{
        ctx.body = {
            code:200,
            message:result
        }
    }).catch(err=>{
        console.log(err)
        ctx.body = {
            code:500,
            message:err
        }
    })
    
})


module.exports = router